package com.algorithm.example.queue.queue;

import java.util.Iterator;

/**
 * <p>
 * 链表队列
 * </p>
 *
 * @author lzt
 * @version 1.0
 * @since 2024/1/24 16:53
 */
public class LinkedListQueue<E> implements Queue<E>, Iterable<E> {
    /**
     * 头部
     */
    private Node<E> head = new Node<>(null, null);;

    /**
     * 尾部
     */
    private Node<E> tail = head;


    /**
     * 个数
     */
    int size;

    /**
     * 容量
     */
    int capacity = Integer.MAX_VALUE;

    {
        tail.next = head;
    }

    private static class Node<E> {
        private E value;
        private Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }

    }

    public LinkedListQueue(int capacity) {
        this.capacity = capacity;
    }

    public LinkedListQueue() {
    }

    @Override
    public boolean offer(E value) {
        if(isFull()) {
            return false;
        }
        Node<E> offer = new Node<>(value, head);
        tail.next = offer;
        tail = offer;
        size++;
        return true;
    }

    @Override
    public E poll() {
        if(isEmpty()) {
            return null;
        }
        Node<E> next = head.next;
        head.next = next.next;
        if(next == tail) {
            tail = head;
        }
        size--;
        return next.value;
    }

    @Override
    public E peek() {
        if(isEmpty()) {
            return null;
        }
        return head.next.value;
    }

    @Override
    public boolean isEmpty() {
        return head.next == head;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p = head.next;
            @Override
            public boolean hasNext() {
                return p != head;
            }

            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }
}
